package org.example;

import javax.net.ssl.*;
import java.io.*;

import java.security.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerMain {

    public static void main(String[] args) {

        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        try {
            //载入keystore
            char[] keystorePassword = "password".toCharArray();
            char[] keyPassword = "password".toCharArray();
            InputStream resourceAsStream = ServerMain.class.getClassLoader().getResourceAsStream("keystore.jks");
            KeyStore keystore = KeyStore.getInstance("JKS");
            keystore.load(resourceAsStream, keystorePassword);

            //创建和初始化SSLContext
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keyPassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keystore);
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            //创建SSLServerSocket
            SSLServerSocketFactory factory = context.getServerSocketFactory();
            SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(12345);

            while (true) {
                //接受客户端连接
                SSLSocket socket = (SSLSocket) serverSocket.accept();
                // 在线程池中处理客户端连接
                executorService.submit(() -> {
                    try {
                        handleClient(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(SSLSocket socket) throws IOException {

        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
        ) {
            // 读取HTTP请求
            StringBuilder request = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null && !line.isEmpty()) {
                request.append(line).append("\r\n");
            }

            System.out.println("Received from client: " + request);

            // 写入HTTP响应
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Content-Type: text/html; charset=UTF-8\r\n" +
                    "Connection: close\r\n" + // Close connection after sending response
                    "\r\n" +
                    "Hello HTTPS!";

            writer.write(response);
            writer.flush();

        } finally {
            // 关闭 socket
            socket.close();
        }
    }
}

